//
//  LogSearchViewController.m
//  StationManager
//
//  Created by 张佳强 on 18/5/11.
//  Copyright © 2018年 Helong. All rights reserved.
//

#import "LogSearchViewController.h"
#import "AFNwebManager.h"
#import <Masonry.h>
#import "LogModel.h"
#import "LogCell.h"
#import "LogSelectView.h"
#import "LogDetailViewController.h"

@interface LogSearchViewController ()<UITableViewDelegate,UITableViewDataSource,LogSelectDelegate>

@property (nonatomic , copy) NSString *allCount;
@property (nonatomic , copy) NSString *xunjianCount;
@property (nonatomic , copy) NSString *yingjiCount;
@property (nonatomic , strong) UILabel *topLabel;
@property (nonatomic , strong) NSMutableArray *dataArray;
@property (nonatomic , strong) UITableView *tableView;
@property (nonatomic , strong) LogSelectView *logSeletView;
@property (nonatomic , strong) UIView *bgView;
@end

@implementation LogSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"维护日志查询";
    
    _dataArray = [NSMutableArray arrayWithCapacity:0];

    [self setRightItem];
    [self setUI];
    
    NSDictionary *params = @{@"userID":[USER_DEFAULT objectForKey:@"userID"],@"stationName":@"",@"taskTypeId":@"全部",@"autoStationNum":@"全部",@"timeStart":[self getStartTime],@"timeEnd":[self getEndTime]};
//    NSLog(@"%@",params);
    [[AFNwebManager shareAFNWebManager] SOAPData:params soapMethod:@"LogListView" success:^(id responseObject) {
        
        
//        NSLog(@"response:%@",responseObject);
        NSArray *array = responseObject[@"data"];
        NSDictionary *dict = array[0];
        _allCount = dict[@"allcount"];
        _xunjianCount = dict[@"xunjian"];
        _yingjiCount = dict[@"yingji"];
        if ([dict.allKeys containsObject:@"k1"]) {
            
            for (NSDictionary *firstDict in dict[@"k1"]) {
                LogModel *model = [[LogModel alloc] init];
                [model setValuesForKeysWithDictionary:firstDict];
                [_dataArray addObject:model];
            }
        }
//        NSLog(@"arrayCount:%zi,all:%@,xunjian:%@,yingjin:%@",_dataArray.count,_allCount,_xunjianCount,_yingjiCount);
        _topLabel.text = [NSString stringWithFormat:@"  应急站点数：%@\t巡检站点数：%@\t总站点数：%@",_yingjiCount,_xunjianCount,_allCount];
        [_tableView reloadData];
    } failure:^{
        
    }];
    
}



-(void)setRightItem{
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 40, 30);
    [rightButton setTitle:@"筛选" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton addTarget:self action:@selector(rightItemClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    
}

-(void)rightItemClick{
    
    NSLog(@"筛选");
    
    
    if (_logSeletView) {
        
        [_logSeletView removeFromSuperview];
    }
    if (_bgView) {
        
        [_bgView removeFromSuperview];
    }
    
    _bgView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    _bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideBgView)];
    [_bgView addGestureRecognizer:tap];

    [self.view addSubview:_bgView];
    
    _logSeletView = [[LogSelectView alloc] initWithFrame:CGRectMake(0, -155, SCREEN_WIDTH, 155)];
    _logSeletView.logSelectDelegate = self;
    [self.view addSubview:_logSeletView];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        _logSeletView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 155);
    }];
    
}

#pragma mark - 点击筛选查询按钮
-(void)sendStationName:(NSString *)name type:(NSString *)type city:(NSString *)city startTime:(NSString *)startTime endTime:(NSString *)endTime{
    
    [_dataArray removeAllObjects];
    [UIView animateWithDuration:0.5 animations:^{
        
        _logSeletView.frame = CGRectMake(0, -155, SCREEN_WIDTH, 155);
        
    } completion:^(BOOL finished) {
        
        [_logSeletView removeFromSuperview];
        [_bgView removeFromSuperview];
        _bgView = nil;
    }];

    NSDictionary *params = @{@"userID":[USER_DEFAULT objectForKey:@"userID"],@"stationName":name,@"taskTypeId":type,@"autoStationNum":city,@"timeStart":startTime,@"timeEnd":endTime};
//    NSLog(@"%@",params);
    
    [[AFNwebManager shareAFNWebManager] SOAPData:params soapMethod:@"LogListView" success:^(id responseObject) {
        
        
//        NSLog(@"response:%@",responseObject);
        NSArray *array = responseObject[@"data"];
        NSDictionary *dict = array[0];
        _allCount = dict[@"allcount"];
        _xunjianCount = dict[@"xunjian"];
        _yingjiCount = dict[@"yingji"];
        if ([dict.allKeys containsObject:@"k1"]) {
            
            for (NSDictionary *firstDict in dict[@"k1"]) {
                LogModel *model = [[LogModel alloc] init];
                [model setValuesForKeysWithDictionary:firstDict];
                [_dataArray addObject:model];
            }
        }
        NSLog(@"arrayCount:%zi,all:%@,xunjian:%@,yingjin:%@",_dataArray.count,_allCount,_xunjianCount,_yingjiCount);
        _topLabel.text = [NSString stringWithFormat:@"  应急站点数：%@\t巡检站点数：%@\t总站点数：%@",_yingjiCount,_xunjianCount,_allCount];
        [_tableView reloadData];
    } failure:^{
        
    }];

}

-(void)hideBgView{
    
    if (_logSeletView) {
        
        [UIView animateWithDuration:0.5 animations:^{
            
            _logSeletView.frame = CGRectMake(0, -155, SCREEN_WIDTH, 155);
            
        } completion:^(BOOL finished) {
            
             [_logSeletView removeFromSuperview];
            [_bgView removeFromSuperview];
            _bgView = nil;
        }];
        
    }
}

-(void)setUI{
    
    
    _topLabel = [[UILabel alloc] init];
    _topLabel.backgroundColor = [UIColor colorWithRed:209/255.0 green:225/255.0 blue:241/255.0 alpha:1.0];
    _topLabel.text = [NSString stringWithFormat:@"  应急站点数：\t巡检站点数：\t总站点数："];
    _topLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:_topLabel];
    
    [_topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-105) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(_topLabel.mas_bottom);
    }];
    
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 10;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *iden = @"logCell";
    LogCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
    if (cell == nil) {
        cell = [[LogCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden];
    }
    
    LogModel *model = _dataArray[indexPath.section];
    cell.stationNumLabel.text = [NSString stringWithFormat:@"台站站号：%@",model.StationID];
    cell.stationNameLabel.text = [NSString stringWithFormat:@"台站站名：%@",model.StationName];
    cell.taskTypeLabel.text = [NSString stringWithFormat:@"任务类别：%@",model.WorkTaskTypeName];
    cell.taskPersonLabel.text = [NSString stringWithFormat:@"下达人：%@",model.WorkTaskXiaDaRen];
    cell.stationTypeLabel.text = [NSString stringWithFormat:@"台站类型：%@",model.stationTypeName];
    cell.reasonLabel.text = [NSString stringWithFormat:@"维护原因：%@",model.YuanYin];
    cell.taskDateLabel.text = [NSString stringWithFormat:@"下达时间：%@",[model.WorkTaskTime substringToIndex:model.WorkTaskTime.length-3]];
    cell.maintainDateLabel.text = [NSString stringWithFormat:@"维护时间：%@",[model.WorkTime substringToIndex:model.WorkTime.length-3]];
    cell.maintainPersonLabel.text = [NSString stringWithFormat:@"台站维护人：%@",model.WorkRenYuans];
    cell.checkLabel.text = @"详情查看";
    
    return cell;
}

//



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 120;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LogDetailViewController *logDetailVC = [[LogDetailViewController alloc] init];
    LogModel *model = _dataArray[indexPath.section];
    logDetailVC.logID = model.jlh;
    logDetailVC.type = model.stationTypeId;
    [self.navigationController pushViewController:logDetailVC animated:YES];
}

- (NSString *)getStartTime{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
   
    NSDateComponents *lastMonthComps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    //    [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期，month day 类推
    NSLog(@"year:%zi",lastMonthComps.year);
//    [lastMonthComps setMonth:-1];
    lastMonthComps.month = lastMonthComps.month-1;
    lastMonthComps.day = 1;
    NSDate *newdate = [calendar dateFromComponents:lastMonthComps];
    //    NSString * startTime = [formatter stringFromDate:newdate];
    
    NSString * realTime2 = [formatter stringFromDate:newdate];
    return realTime2;
}
- (NSString *)getEndTime{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    //    NSString * endTIme = [formatter stringFromDate:date];
    
    NSString * realTime2 = [formatter stringFromDate:date];
    return realTime2;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
